using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Web.Services;
using System.Xml;
using System.Xml.Xsl;

using umlungu.engineX;
using umlungu.engineX.emailX;
using umlungu.engineX.webserviceX;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2008-06-14
	Status:		release	
	Version:	2.0.0
	Build:		20080614
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/

/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20080614:	Initial release.
	---------------------------------------------------------------------------	*/

namespace umlungu.engineX.blogX.WebsiteX {
	/// <summary>
	/// umlungu WebsiteServiceX web services
	/// </summary>
	[WebService(Namespace="http://www.umlungu.com/engineX/")]
	public class WebsiteServiceX : x_webservice {
		#region Private properties
		//private string DSNid = "WebsiteXDSN";
		#endregion

		#region Constructors/Destructors
		/// <summary>Constructor</summary>
		public WebsiteServiceX() : base() {
			ID = "WebsiteXX";
		}
		#endregion
		
		#region Web service methods for sending email
		/// <summary>
		/// Method to send a simple email
		/// </summary>
		/// <returns>Returns an XmlDocument containing the reseller list</returns>
		[WebMethod(Description = "Method to send a simple email")]
		public XmlDocument SendEmail(string To, string From, string Subject, string Message) {	//, string Server
			try {
				x_email thisemail = new x_email(To, From, Subject);
				//if (Server != "")
				//	thisemail.Server = Server;
				thisemail.Send(Message);
				AddOk();
				AddNode("To", To);
				AddNode("From", From);
				AddNode("Subject", Subject);
				AddNode("Message", Message);
			} catch (Exception e) {
				AddError(e);
			}
			return Result;
		}
		/// <summary>
		/// Method to send an email to users on a list
		/// </summary>
		/// <returns>Returns an XmlDocument containing the subscriber list</returns>
		/// <param name="excelfile">The name of the excel file (including extension)</param>
		/// <param name="xslfile">The name of the xsl template file in the templates directory(including extension)</param>
		/// <param name="subject">The subject of the email</param>
		/// <param name="from">The from address of the email</param>
		[WebMethod(Description = "Method to send an email to users on a list in an excel file with named area of 'User'")]
		public XmlDocument SendEmailList(string excelfile, string xslfile, string subject, string from) {
			try {
				XmlDocument users = getUsers(excelfile);
				XslCompiledTransform template = getTemplate(xslfile);
				foreach (XmlNode user in users.SelectNodes("//Users/User")) {
					DateTime timestamp = DateTime.Now;
					XmlElement subEl = user as XmlElement;
					subEl.SetAttribute("datetime", timestamp.ToString("s"));
					XmlDocument thissub = new XmlDocument();
					thissub.LoadXml(user.OuterXml);
					string status = send(thissub, template, subject, from);
					if (status == "") {
						subEl.SetAttribute("status", "ok");
					} else {
						subEl.SetAttribute("status", "notok");
						subEl.AppendChild(users.CreateElement("Error")).InnerText = status;
					}
				}
				_AddOk(users);
			} catch (Exception e) {
				AddError(e);
			}
			return Result;
		}
		/// <summary>
		/// Method to send an email to users on a list
		/// </summary>
		/// <returns>Returns an XmlDocument containing the subscriber list</returns>
		/// <param name="excelfile">The name of the excel file (including extension)</param>
		[WebMethod(Description = "Method to get a list of users in an excel file with named area of 'User'")]
		public XmlDocument SendList(string excelfile) {
			try {
				XmlDocument users = getUsers(excelfile);
				_AddOk(users);
			} catch (Exception e) {
				AddError(e);
			}
			return Result;
		}
		private XslCompiledTransform getTemplate(string thisfile) {
			XslCompiledTransform templ = new XslCompiledTransform();
			templ.Load(Server.MapPath(String.Concat("templates/", thisfile)));
			return (templ);
		}
		public XmlDocument getUsers(string excelfile) {
			XmlDocument users = new XmlDocument();
			string path = Server.MapPath(excelfile);
			users.LoadXml(getUserXml(path));
			//XmlElement usrs = (XmlElement)users.SelectSingleNode("//Users");
			return users;
		}
		private string getUserXml(string filepath) {
			return getExcelXml(filepath, "Users", "Users", "User");
		}
		/// <summary>
		/// Method to read a named object in a spreadsheet (using ADO.Net) and return an xml string
		/// </summary>
		private string getExcelXml(string filepath, string excelObjName, string parentName, string childName) {
			String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;";
			using (OleDbConnection objConn = new OleDbConnection(sConnectionString)) {
				objConn.Open();
				// Get all users - ie cells defined by the name excelObjName
				OleDbCommand objCmdSelect = new OleDbCommand(String.Concat("SELECT * FROM ", excelObjName), objConn);
				OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
				objAdapter1.SelectCommand = objCmdSelect;

				DataSet objDataset1 = new DataSet(parentName);
				objAdapter1.Fill(objDataset1, childName);
				objConn.Close();
				return objDataset1.GetXml();
			}
		}
		private string send(XmlDocument emailXml, XslCompiledTransform emailTemplate, string subject, string from) {
			string status = "";
			try {
				XmlNode subscriber = emailXml.SelectSingleNode("/User");
				string email = subscriber.SelectSingleNode("Email").InnerText;
				x_email thisemail = new x_email();
				thisemail.Subject = subject;
				thisemail.To = email;
				thisemail.From = from;
				thisemail.Type = x_emailtype.html;
				thisemail.Send(emailXml, emailTemplate);
			} catch (System.Exception e) {
				status = e.Message;
			}
			return status;
		}
		#endregion
		
	}
}
